﻿using System;
using System.Windows;
using System.Windows.Markup;

namespace FrontDisplay.Localization
{
    public class TranslateExtension : MarkupExtension
    {
        private DependencyObject _target;
        private DependencyProperty _property;

        public string Key { get; set; }

        public bool IsAutoUpdate { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (IsAutoUpdate)
            {
                IProvideValueTarget service = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
                if (service == null)
                {
                    throw new InvalidOperationException("IProvideValueTarget service is unavailable");
                }
                DependencyProperty property = service.TargetProperty as DependencyProperty;
                if (property == null)
                {
                    //throw new ArgumentException("Target property must be of type DependencyProperty");
                }
                DependencyObject target = service.TargetObject as DependencyObject;
                if (target == null)
                {
                    //return this;
                }

                _target = target;
                _property = property;

                Def.Localization.CultureChanged += LocalizationCultureChanged;
            }
            return Def.Localization.GetString(Key);
        }

        private void LocalizationCultureChanged(System.Globalization.CultureInfo cultureInfo)
        {
            _target.SetValue(_property, Def.Localization.GetString(Key));
        }
    }
}
